<?php
session_start();
if (!isset($_SESSION['admin'])) { header('Location: index.php'); exit; }
$pid = $_GET['pid'] ?? '';
$projects = file_exists('../data/projects.json') ? json_decode(file_get_contents('../data/projects.json'), true) : [];
if ($pid && !isset($projects[$pid])) { echo '项目不存在'; exit; }
$dir = $pid ? "../data/project_$pid/" : '../data/';
$dataFile = $dir.'versions.json';
$uploadDir = $dir.'uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
$versions = file_exists($dataFile) ? json_decode(file_get_contents($dataFile), true) : [];
// 处理上传
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['apk'])) {
    $file = $_FILES['apk'];
    if ($file['error'] === 0) {
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if ($ext === 'apk') {
            $fname = uniqid('app_').'.apk';
            move_uploaded_file($file['tmp_name'], $uploadDir.$fname);
            $apkUrl = "data/project_$pid/uploads/$fname";
            $_POST['url'] = $apkUrl;
            // 自动填写表单
        }
    }
}
// 添加版本
if (isset($_POST['add'])) {
    $versions[] = [
        'name' => $_POST['name'],
        'version' => $_POST['version'],
        'date' => $_POST['date'],
        'url' => $_POST['url']
    ];
    file_put_contents($dataFile, json_encode($versions, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
    header('Location: versions.php?pid='.$pid); exit;
}
// 删除
if (isset($_GET['del'])) {
    array_splice($versions, $_GET['del'], 1);
    file_put_contents($dataFile, json_encode($versions, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
    header('Location: versions.php?pid='.$pid); exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>历史版本管理</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
    .upload-area {
        border: 2px dashed #007aff;
        border-radius: 12px;
        background: #f8f9fa;
        padding: 36px 0;
        text-align: center;
        margin-bottom: 24px;
        cursor: pointer;
        transition: border-color 0.2s;
    }
    .upload-area.dragover { border-color: #005bb5; background: #eaf4ff; }
    .upload-area input[type=file] { display: none; }
    .upload-btn-lg { font-size: 1.2rem; padding: 16px 32px; }
    </style>
</head>
<body>
<div class="container py-4">
    <h4 class="mb-3">历史版本管理<?= $pid ? ' - '.htmlspecialchars($projects[$pid]['name']) : '' ?></h4>
    <div class="upload-area mb-4" id="upload-area">
        <form method="post" enctype="multipart/form-data" id="upload-form">
            <label for="apk-upload" class="upload-btn-lg btn btn-success mb-2">点击或拖入APK文件上传新版本</label>
            <input type="file" name="apk" id="apk-upload" accept=".apk">
            <div class="text-muted">支持直接拖拽APK文件到此区域</div>
        </form>
        <div id="upload-result" class="mt-2"></div>
    </div>
    <form method="post" class="row g-2 align-items-end mb-4 bg-white p-3 rounded shadow-sm" id="version-form">
        <div class="col-md-3">
            <label class="form-label">名称</label>
            <input name="name" class="form-control" required>
        </div>
        <div class="col-md-2">
            <label class="form-label">版本号</label>
            <input name="version" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label">更新时间</label>
            <input name="date" type="date" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label">下载链接</label>
            <input name="url" class="form-control" id="apk-url" required>
        </div>
        <div class="d-flex justify-content-end gap-3 mt-4">
            <button type="submit" name="add" class="btn btn-primary btn-lg px-5">添加</button>
            <a href="project_dashboard.php?pid=<?=$pid?>" class="btn btn-outline-secondary btn-lg px-5">返回</a>
        </div>
    </form>
    <table class="table table-bordered table-hover align-middle bg-white">
        <thead><tr><th>名称</th><th>版本号</th><th>更新时间</th><th>下载链接</th><th>操作</th></tr></thead>
        <tbody>
        <?php foreach($versions as $k=>$v): ?>
        <tr>
            <td><?=htmlspecialchars($v['name'])?></td>
            <td><?=htmlspecialchars($v['version'])?></td>
            <td><?=htmlspecialchars($v['date'])?></td>
            <td><a href="<?=htmlspecialchars($v['url'])?>" target="_blank">下载</a></td>
            <td>
                <a href="?pid=<?=$pid?>&del=<?=$k?>" class="btn btn-danger btn-sm" onclick="return confirm('确定删除？')">删除</a>
                <a href="../download.php?pid=<?=$pid?>&ver=<?=urlencode($v['version'])?>" class="btn btn-info btn-sm ms-1" target="_blank">预览下载页</a>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<script>
// 拖拽上传逻辑
const uploadArea = document.getElementById('upload-area');
const fileInput = document.getElementById('apk-upload');
const uploadForm = document.getElementById('upload-form');
const uploadResult = document.getElementById('upload-result');
const apkUrlInput = document.getElementById('apk-url');

uploadArea.addEventListener('dragover', function(e) {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', function(e) {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', function(e) {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    if (e.dataTransfer.files.length) {
        fileInput.files = e.dataTransfer.files;
        uploadForm.submit();
    }
});
fileInput.onchange = function() {
    if (fileInput.files.length) uploadForm.submit();
};
// 上传后自动填写下载链接
<?php if (isset($apkUrl)): ?>
document.getElementById('apk-url').value = '<?=$apkUrl?>';
uploadResult.innerHTML = '<span class="text-success">上传成功，下载链接已自动填写！</span>';
<?php endif; ?>
</script>
</body>
</html> 